import configparser
import datetime
import json
import os
import random
import string
import time
import sys
import getopt
import allure
# import cx_Oracle
import re
import jsonpath
import pymysql
import requests
import yaml
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.support.wait import WebDriverWait


def get_test_case():
    case = getopt.getopt(sys.argv, '-h')
    return case[1][3]


class BasePage:
    sysErrorFlag = 0

    def __init__(self, driver):
        # self.driver = webdriver.Chrome()
        self.driver = driver

    def get(self, url):
        self.driver.get(url)

    def quite_(self):
        self.driver.quite()

    # 删除本地文件
    def del_localFile(self, file_path):
        if os.path.isfile(file_path):
            os.remove(file_path)

    # def Oracle_select(self, connectInfo, sql):
    #     os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
    #     db = cx_Oracle.connect(connectInfo)
    #     cursor = db.cursor()
    #     cursor.execute(sql)
    #     row = cursor.fetchone()
    #     print(row)
    #     cursor.close()
    #     db.close()
    #     return row

    # def Oracle_update(self, connectInfo, sql):
    #     os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
    #     db = cx_Oracle.connect(connectInfo)
    #     cursor = db.cursor()
    #     cursor.execute('Begin ' + sql + ' END;')  # 支持多条sql
    #     db.commit()
    #     cursor.close()
    #     db.close()

    # Mysql查询
    def mysql_select(self, query, db_config):
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor(pymysql.cursors.DictCursor)
        cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result

    # 多条sql
    def mysql_selects(self, query_list, db_config):
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()
        for query in query_list:
            cursor.execute(query)
        result = cursor.fetchall()
        cursor.close()
        conn.close()
        return result[0]

    def executeCase(self, caseId, result):
        data = {
            'test_plan_id': 1166076771001000086,
            'tcase_id': '116607677100{}'.format(caseId),
            'workspace_id': 66076771,
            'result_status': result,
            'last_executor': 'AutoTest'
        }
        requests.post('https://api.tapd.cn/tcase_instance/execute', data=data,
                      auth=('TMBBDL', '202AE6FA-6D3C-D6CB-63FA-B69255D2C248'))

    def update_yaml(self, path, key, value):
        with open(path, 'r', encoding='utf-8') as f:
            lines = []
            for line in f.readlines():
                if line != '\n':
                    lines.append(line)

        with open(path, 'w', encoding='utf-8') as f:
            flag = 0
            for line in lines:
                if key in line and '#' and '$' not in line:
                    leftstr = line.split(":")[0]
                    newline = "{0}: {1}".format(leftstr, value)
                    # line = newline
                    f.write('%s\n' % newline)
                    flag = 1
                else:
                    f.write('%s' % line)

            return flag

    def isElementExist(self, loc):
        flag = True
        try:
            # self.driver.find_element(method, value)
            # self.find_el(loc)
            el = WebDriverWait(self.driver, 10, 0.5).until(lambda el: self.driver.find_element(*loc)
                                                           , message='没有找到目标参数')
            return el
        except:
            flag = False
            self.screenshot()
            return flag

    # 用于判断不同客户配置不同，导致流程不同，无法控制，例如：运输成本计费里供应商是否有此运力类型报价； 以及判断筛选条件是否有展开
    def isElementExist2(self, loc):
        flag = True
        try:
            # self.driver.find_element(method, value)
            # self.find_el(loc)
            el = WebDriverWait(self.driver, 2, 0.5).until(lambda el: self.driver.find_element(*loc)
                                                          , message='没有找到目标参数')
            return el
        except:
            flag = False
            self.screenshot()
            return flag

    def isErrorExist(self, loc):
        try:
            el = WebDriverWait(self.driver, 0.8, 0.2).until(lambda el: self.driver.find_element(*loc)
                                                            , message='没有找到目标参数')
            return el
        except:
            return False

    # 页面缩放
    def page_zoom_in(self):
        self.driver.execute_script("document.body.style.zoom='0.15';")

    def page_zoom_in_back(self):
        self.driver.execute_script("document.body.style.zoom='1';")

    def web_refresh(self):
        self.driver.refresh()

    def find_el(self, loc):
        try:
            el = WebDriverWait(self.driver, 40, 1).until(lambda el: self.driver.find_element(*loc)
                                                         , message='没有找到目标参数')
            # 目标元素加高亮
            self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", el,
                                       "background: yellow;")
            return el
        except:
            self.screenshot()
            raise AssertionError

    def find_els(self, loc):
        try:
            return WebDriverWait(self.driver, 60, 0.5).until(lambda el: self.driver.find_elements(*loc)
                                                             , message='没有找到目标参数')
        except:
            self.screenshot()
            raise AssertionError

    def do_click(self, loc):
        el = self.find_el(loc)
        try:
            el.click()
            self.errorShoot()
            # time.sleep(0.5)
        except:
            self.screenshot()
            raise AssertionError
        try:
            self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", el,
                                       "background: null;")
        except:
            pass

    def js_click(self, loc):
        el = self.find_el(loc)
        self.driver.execute_script("arguments[0].click();", el)
        time.sleep(0.5)

    def js_sendkeys(self, loc, text):
        el = self.find_el(loc)
        self.driver.execute_script("arguments[0].value = arguments[1];", el, text)
        time.sleep(0.5)

    def do_sendkeys(self, loc, txt):
        el = self.find_el(loc)
        el.send_keys(txt)
        time.sleep(0.5)
        try:
            self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", el,
                                       "background: null;")
        except:
            pass
        # self.errorShoot()

    def clear_sendkeys(self, loc, txt):
        el = self.find_el(loc)
        el.send_keys(Keys.CONTROL + "a")
        el.send_keys(Keys.DELETE)
        el.send_keys(txt)
        time.sleep(0.5)
        self.driver.execute_script("arguments[0].setAttribute('style', arguments[1]);", el,
                                   "background: null;")

    # 下拉选择
    def dropbox_select(self, loc1, loc2):
        self.do_click(loc1)
        self.do_click(loc2)

    def multiple_dropbox_select(self, *loc: tuple):
        for i in loc:
            self.do_click(i)

    def screenshot(self):
        now = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
        screenshot = 'Error_' + now + '.png'
        # screenshot_abspath = os.path.dirname(os.path.dirname(__file__)) + r'\report\\' + screenshot
        screenshot_abspath = f'/root/.jenkins/workspace/{get_test_case()}/' + screenshot
        self.driver.get_screenshot_as_file(screenshot_abspath)
        allure.attach.file(screenshot_abspath, name=screenshot, attachment_type=allure.attachment_type.PNG)

    # 缺陷提交
    def exception(self, caseID, regularEx, e, tittle, env):
        if BasePage.sysErrorFlag == 1:
            raise SystemError
        else:
            self.screenshot()
            precondition = self.get_caseInfo(caseID, 'precondition')
            steps = re.findall(regularEx, self.get_caseInfo(caseID, 'steps'))
            actual = str(e)
            self.create_bug(tittle, precondition, env, steps[0][0], actual)
            raise AssertionError

    # 关闭保单平台选项卡
    def close_tab(self):
        try:
            self.driver.find_element('xpath', "(//i[@class='anticon anticon-close'])[1]")
            self.do_click(('xpath', "(//i[@class='anticon anticon-close'])[1]"))
            self.close_tab()
        except:
            pass

    def errorShoot_old(self):
        error_info = ("xpath", "//div[@class='ant-message-custom-content ant-message-error']")
        warning_info = ("xpath", "//div[@class='ant-message-custom-content ant-message-warning']")
        if self.isErrorExist(error_info):
            error_msg = self.driver.find_element('xpath',
                                                 "//div[@class='ant-message-custom-content ant-message-error']/span[2]").text
            ignore_error = ['该供应商无此运力类型报价，请手动输入计费金额！',
                            '请手动输入金额']
            if error_msg in ignore_error:
                pass
            else:
                raise AssertionError
        elif self.isErrorExist(warning_info):
            raise AssertionError

    def errorShoot(self):
        # error_info = ("xpath", "//div[@class='ant-message-custom-content ant-message-error']")
        # warning_info = ("xpath", "//div[@class='ant-message-custom-content ant-message-warning']")
        notice_el = ("xpath", "//div[@class='ant-message-notice-content']")
        if self.isErrorExist(notice_el):
            if self.driver.find_elements('xpath', "//div[@class='ant-message-custom-content ant-message-success']"):
                pass
            else:
                error_msg = self.driver.find_element('xpath',
                                                     "//div[@class='ant-message-notice-content']/div/span[2]").text
                ignore_error = ['该供应商无此运力类型报价，请手动输入计费金额！',
                                '请手动输入金额']
                if error_msg in ignore_error:
                    pass
                else:
                    raise AssertionError
        else:
            pass

    # 荣庆系统无法做到url跳转，每次使用点击菜单的方式
    def menu_select(self, exp_el, *loc: tuple):
        for i in loc:
            self.do_click(i)
        assert self.isElementExist(exp_el)

    def random_str(self, length):
        digits = string.digits
        lowercase_letters = string.ascii_lowercase
        uppercase_letters = string.ascii_uppercase
        random_chars = [random.choice(digits), random.choice(lowercase_letters), random.choice(uppercase_letters)]
        for i in range(length - 3):
            random_chars.append(random.choice(digits + lowercase_letters + uppercase_letters))
        random.shuffle(random_chars)
        return ''.join(random_chars)

    def random_num(self, num):
        return ''.join(random.sample(string.digits, num))


if __name__ == '__main__':
    # print(os.path.join(os.path.abspath(os.path.dirname(os.getcwd()) + os.path.sep + "."), 'report'))
    driver = webdriver.Chrome()

    # # 获取allure report结果
    # data_file_path = f'/usr/Application/Jenkins/workspace/{build_info[2]}/allure-report/data/categories.json'
    # with open(data_file_path, 'r') as file:
    #     json_content = file.read()
    # data = json.loads(json_content)
